// #ifdef H5
import jWeixin from 'jweixin-module'
// #endif

const amapFile = require('../components/amap-wx.130.js')
const myAmapFun = new amapFile.AMapWX({
	key: '79d7b09b344a5c727283d35ab6926ffe'
}); //创建一个实例化对象

export const getWeather = () => {
	return new Promise((resolve, reject) => {
		myAmapFun.getWeather({
			success: function(data) {
				resolve(data)
			},
			fail: function(info) {
				reject(info)
			}
		})
	})
}

export const isWeiXin = () => {
	let target = navigator?.userAgent.toLowerCase();
	return /micromessenger/.test(target);
}

export const getCode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			success: async ({
				code
			}) => {
				resolve(code)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

export const payment = (pay_info) => {
	console.info({
		pay_info
	})
	return new Promise((resolve, reject) => {
		const params = pay_info.data ? pay_info.data : pay_info
		// #ifdef MP
		// #ifdef MP-TOUTIAO
		let param = {
			provider: 'toutiao',
			orderInfo: params,
			service: 5
		};
		// #endif
		// #ifdef MP-WEIXIN

		let param = params;
		// #endif

		uni.requestPayment({
			...param,
			success: res => {
				// #ifdef MP-WEIXIN
				resolve()
				// #endif
				// #ifdef MP-TOUTIAO
				if (res.code == 0) {
					resolve()
				} else {
					reject('支付失败')
				}
				// #endif

			},
			fail: err => {
				console.info({
					err
				})
				reject(err)
			}
		});
		// #endif

		// #ifdef H5
		if (isWeiXin()) {
			jWeixin.chooseWXPay({
				...params,
				timestamp: params.timeStamp,
				success: (res) => {
					resolve(true)
				},
				fail: (err) => {
					console.info({
						err
					})
					reject(err)
				}
			});
		} else {
			window.location.href = params.mweb_url
			resolve(true)
		}
		// #endif
	})
}

export const getLocation = () => {
	return new Promise((resolve, reject) => {
		// #ifdef MP || APP-PLUS
		// #ifdef MP-WEIXIN
		// @ts-ignore
		// const locationType = 'getFuzzyLocation';
		// #endif
		// #ifndef MP-WEIXIN
		// @ts-ignore
		// const locationType = 'getLocation';
		//#endif

		const locationType = 'getLocation';

		uni[locationType]({
			type: "gcj02",
			success: (res) => {
				console.info(res)
				resolve(res)
			},
			fail: (err) => {
				console.info({
					err
				})
				uni.showToast({
					title: "请打开手机定位功能再试",
					icon: "error"
				})
				reject(err)
			}
		})
		//#endif

		// #ifdef H5
		if (isWeiXin()) {
			jWeixin.getLocation({
				type: "gcj02",
				success: (res) => {
					resolve(res)
				},
				cancel: (err) => {
					reject()
				},
				fail: (err) => {
					console.info('officon location error:', err)
					uni.showToast({
						title: "请打开手机定位功能再试",
						icon: "error"
					})
					reject(err)
				},
			});
		} else {
			uni.getLocation({
				type: "gcj02",
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					uni.showToast({
						title: "请打开手机定位功能再试",
						icon: "error"
					})
					reject(err)
				}
			})
		}
		//#endif
	})
}

export const saveImage = async (tempFilePath) => {
	//#ifdef MP
	if (!tempFilePath) return;
	//判断用户授权
	let result = await authorize('scope.writePhotosAlbum');
	if (result !== true) {
		let {
			authSetting
		} = await openSetting('请同意授权保存到相册');
		if (!authSetting['scope.writePhotosAlbum']) {
			return toast('你已拒绝授权，无法保存到相册');
		}
	}
	uni.saveImageToPhotosAlbum({
		filePath: tempFilePath,
		success: res => {
			uni.showToast({
				title: '已保存到相册',
				icon: 'success',
				duration: 2000
			});
		}
	});
	//#endif

	//#ifdef H5
	const arr = tempFilePath.split(',');
	const bytes = atob(arr[1]);
	let ab = new ArrayBuffer(bytes.length);
	let ia = new Uint8Array(ab);
	for (let i = 0; i < bytes.length; i++) {
		ia[i] = bytes.charCodeAt(i);
	}
	const blob = new Blob([ab], {
		type: 'application/octet-stream'
	});
	const url = URL.createObjectURL(blob);
	const a = document.createElement('a');
	a.href = url;
	a.download = new Date().valueOf() + ".png";
	const e = document.createEvent('MouseEvents');
	e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	a.dispatchEvent(e);
	URL.revokeObjectURL(url);
	//#endif
}

export const authorize = (scope) => {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: scope,
			success: (res) => {
				resolve(true)
			},
			fail: (err) => {
				resolve(err)
			}
		})
	})
}